<?php

namespace app\db\model;

use think\Db;
use think\Model;

class DbQuestionOption extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $dbName     = 'db_question_option';
    # --------------------------------- 查询类接口 START------------------------------------
    /**
     * 获取模板信息
     * @param int  $option_id 变量ID
     * @author MSQ 2021-8-2
    **/
    public function getDetails($option_id = 0,$field = '*')
    {
        if ($field && $field != '*' && count(explode(',', $field)) == 1) {
            // 只取一个字段
            $info = $this->where(['id' => $option_id])->value($field);
        }else{
            $info = db($this->dbName)->field($field)->where(['id' => $option_id])->find();
        }
        
        return $info;
    }
    /**
     * 生成随机option_key
     * @param int  $option_key 指定key
     * @author MSQ 2021-8-2
    **/
    public function getOptionKey($question_id = 0,$option_key = '')
    {
        if (!$option_key) $option_key = uniqid().'_'.$question_id;
        # 验证唯一性
        $isExist = $this->where(['option_key' => $option_key])->value('id');

        if ($isExist) $this->getOptionKey();
        return $option_key;
    }
    /**
     * 根据变量id获取选项
     * @param int  $question_id 变量id
     * @author MSQ 2021-8-12
    **/
    public function getQuestionOptionByQid($question_id = 0)
    {
        if (!$question_id) return false;
        $where = [
            'question_id' => $question_id,
            'status'      => 1,
        ];
        $list = db($this->dbName)->where($where)->select();
        return $list;
    }
    /**
     * 自定义SQL
     * @author MSQ 2021-9-8
     */
    public function customQuery($where = [],$field = '')
    {
        $where['status'] = 1;

        if ($field && $field != '*' && count(explode(',', $field)) == 1) {
            // 只取一个字段
            $info = $this->where($where)->column($field);
        }else{
            $info = db($this->dbName)->field($field)->where($where)->select();
        }

        return $info;
    }
    # ---------------------------------- 查询类接口 END-------------------------------------

    # ------------------------------ 数据处理类接口 START ----------------------------------
    /**
     * 创建选项
     * @param int  $option_key 指定key
     * @author MSQ 2021-8-2
    **/
    public function createOption($question_id = 0,$option_list = [],$template_id = 0,$usercare_id = 0)
    {
        if (!$question_id || !$option_list) return false;

        $addData = [];
        $count = count($option_list);
        foreach ($option_list as $k => $v) {
            if ($v['option_name'] === '' || $v['option_name'] === NULL) return false;
            
            $is_other = isset($v['is_other']) ? $v['is_other'] : 0;

            # 检测选项是否已存在
            $where = [
                'option_name' => $v['option_name'],
                'question_id' => $question_id,
                'status'      => 1,
            ];
            $info = $this->where($where)->find();
            if ($info) {
                if ($info['weight'] != $count || $info['is_other'] != $is_other) {
                    # 选项已存在但weight或is_other不同 更新选项
                    $saveData = ['weight' => $count,'is_other' => $is_other];
                    $this->update($saveData,['id' => $info['id']]);
                }
                continue;
            }

            $option_key = isset($v['option_key']) && $v['option_key'] ? $v['option_key'].'&'.uniqid() : $this->getOptionKey($question_id);
            $addData[] = [
                'option_name' => $v['option_name'],
                'option_key'  => $option_key,
                'question_id' => $question_id,
                'is_other'    => $is_other,
                'template_id' => $template_id,
                'usercare_id' => $usercare_id,
                'create_type' => isset($v['create_type']) ? $v['create_type'] : 0,
                'weight'      => $count,
            ];
            --$count;
        }
        if (!$addData) return true;

        return $this->setAttr('id',null)->isUpdate(false)->saveAll($addData);
        // return $this->saveAll($addData);
    }
    /**
     * 删除选项及关联选项
     * @param int  $option_ids 删除选项的id
     * @author MSQ 2021-8-12
    **/
    public function deleteOptions($option_ids = [],$template_id = 0)
    {
        if (!is_array($option_ids)) $option_ids = [$option_ids];

        $where = [
            'id'     => ['IN',$option_ids],
            'status' => 1
        ];
        $delRes = $this->update(['status' => 0],$where);
        if ($delRes === false) return false;

        if ($template_id) {
            # 删除关联表 编辑变量时删除多余选项 会先删总表再删关联表
            $delRelationRes = model('DbTemplateRelationQuestionOption')->deleteByTemplateAndOptionIds($template_id,$option_ids);
            if ($delRelationRes === false) return false;
        }
        return true;
    }
    /**
     * 添加数据
     * @author MSQ 2021-9-1
     */
    public function addData($data = [])
    {
        if (!$data) return false;
        
        $this->setAttr('id',null)->isUpdate(false)->save($data);
        if (!isset($this->id)) return false;

        return $this->id;
    }
    # -------------------------------- 数据处理类接口 END ----------------------------------

    
}
